package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户端JWT令牌校验拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 非控制器方法直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 1. 从请求头获取用户端令牌（对应配置中的user-token-name）
        String token = request.getHeader(jwtProperties.getUserTokenName());
        log.info("用户端JWT令牌：{}", token);

        // 2. 校验令牌
        try {
            // 解析令牌获取claims
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            // 从claims中提取用户ID
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前登录用户ID：{}", userId);
            // 3. 将用户ID存入ThreadLocal
            BaseContext.setCurrentId(userId);
            // 校验通过，放行
            return true;
        } catch (Exception e) {
            // 令牌无效或过期，返回401未授权
            response.setStatus(401);
            return false;
        }
    }
}